<template>
  <div class="main">
    <!-- 搜索模块 -->
    <el-card shadow="always">
      <el-form class="seachForm">
        <el-form-item label="用户名:">
          <el-input v-model="userTit.username" />
        </el-form-item>
        <el-form-item>
          <template #default>
            <el-button
              type="primary"
              :disabled="!userTit.username.length"
              @click="search"
            >
              搜索
            </el-button>
            <el-button type="success" @click="userTit.username = ''">
              重置
            </el-button>
          </template>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 信息模块 -->
    <el-card shadow="always">
      <!-- 添加与删除按钮 -->
      <el-button type="success" @click="addUser">添加</el-button>
      <el-button
        type="danger"
        @click="deletUserList"
        :disabled="selectIdArr.length ? false : true"
      >
        批量删除
      </el-button>
      <!-- table区域 -->
      <el-table
        :data="userList"
        style="margin: 30px 0"
        :border="true"
        :select-on-indeterminate="true"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column prop="id" label="id" width="100" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="roleName" label="用户角色" width="240" />
        <el-table-column prop="updateTime" label="更新时间" width="170" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" icon="SetUp" @click="distributeUser(row)">
              分配角色
            </el-button>
            <el-button type="warning" icon="edit" @click="editUser(row)">
              编辑
            </el-button>
            <el-popconfirm title="确认删除吗" @confirm="deletUser(row)">
              <template #reference>
                <el-button type="danger" icon="DeleteFilled">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="userTit.page"
        v-model:page-size="userTit.limit"
        :page-sizes="[2, 5, 6, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 添加用户信息 -->
    <el-drawer v-model="toggleDrawer">
      <!-- 标题 -->
      <template #header>
        <h3>用户信息添加</h3>
      </template>
      <!-- 内容主题 -->
      <template #default>
        <el-form
          ref="userForm"
          :model="addUserOrUpdate"
          :rules="rulesUserForm"
          label-width="120px"
        >
          <el-form-item label="用户姓名" prop="username">
            <el-input
              v-model="addUserOrUpdate.username"
              placeholder="输入用户名"
            />
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              v-model="addUserOrUpdate.name"
              placeholder="输入用户昵称"
            />
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input
              type="password"
              v-model="addUserOrUpdate.password"
              placeholder="输入密码"
            />
          </el-form-item>
          <el-form-item>
            <!-- 底部按钮 -->
            <el-button @click="cancelAdd">取消</el-button>
            <el-button type="primary" @click="save">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </el-drawer>
    <!-- 职位分配 -->
    <el-drawer v-model="toggleDrawer1">
      <!-- 标题 -->
      <template #header>
        <h3>用户职位分配</h3>
      </template>
      <!-- 内容主题 -->
      <template #default>
        <el-form :model="addUserOrUpdate">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              v-model="addUserOrUpdate.username"
              placeholder="输入用户名"
              disabled="true"
            />
          </el-form-item>
          <el-form-item label="角色列表">
            <!-- 全选 -->
            <el-checkbox
              v-model="checkAll"
              @change="handleCheckAllChange"
              :indeterminate="indeterminate"
            >
              全选
            </el-checkbox>
            <!-- 复选 -->
            <el-checkbox-group v-model="curRoleList">
              <el-checkbox
                v-for="item in AllRoleList"
                :key="item.id"
                :label="item"
              >
                {{ item.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <!-- 底部 -->
      <template #footer>
        <el-button @click="toggleDrawer1 = false">取消</el-button>
        <el-button type="primary" @click="saveRole">保存</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
/* 获取接口请求地址 */
import {
  reqGetUserListAPI,
  reqAddOrUpdateUserAPI,
  reqGetAllRoleListAPI,
  reqSetUserRoleAPI,
  reqDeletUserAPI,
  reqDeletUserListAPI,
} from '@/apis/permission/user/index'
/* 获取TS类型 */
import {
  records,
  resAllUserList,
  resAllRolesList,
  AllRole,
} from '@/apis/permission/user/userTypes'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { onMounted, reactive, ref, watch } from 'vue'
/* 页面已加载就获取数据 */
onMounted(() => getUserList(userTit.page, userTit.limit, userTit.username))
/* 获取用户数据初始化 */
const userTit = reactive({
  page: 1 /* 当前页数 */,
  limit: 10 /* 每页显示数量 */,
  username: '',
})
/* 存储获取到的全部用户数据 */
const userList = ref<records[]>([])
/* 切换添加用户 抽屉显示*/
const toggleDrawer = ref<boolean>(false)
/* 切换添加用户 抽屉显示 */
const toggleDrawer1 = ref<boolean>(false)
/* 用户数据列表总条数 */
let total = ref<string>('')
/* 搜集添加用户的信息 */
const addUserOrUpdate = reactive<records>({
  username: '',
  name: '',
  password: '',
})
/* 表单元素 */
const userForm = ref<FormInstance>()
/* 表单校验规则 */
const rulesUserForm = reactive<FormRules>({
  /* 用户名 */
  username: [
    { required: true, message: '请填写用户姓名', trigger: 'blur' },
    { min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  /* 用户昵称 */
  name: [
    { required: true, message: '请填写用户昵称', trigger: 'blur' },
    { min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  /* 用户密码 */
  password: [
    { required: true, message: '请填写用户密码', trigger: 'blur' },
    { min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
})
/* 分配角色全选按钮 */
const checkAll = ref<boolean>(false)
/* 不确定样式 */
const indeterminate = ref<boolean>(false)
/* 所有角色权限 */
const AllRoleList = ref<AllRole>([])
/* 当前角色已有权限 */
const curRoleList = ref<AllRole>([])
/* 准备一个数组存储批量删除的用户的ID */
const selectIdArr = ref<records[]>([])
/* 获取全部用户信息 */
const getUserList = async (page: number, limit: number, username: string) => {
  const { data: res }: resAllUserList = await reqGetUserListAPI(
    page,
    limit,
    username,
  )
  /* 对返回回来的数据进行校验 */
  if (res.code != 200) ElMessage.error('获取失败')
  /* 储存所有用户的数据 */
  userList.value = res.data.records
  total.value = res.data.total as string
}
/* 点击复选框时触发 */
const handleSelectionChange = async (val: any) => {
  selectIdArr.value = val
}
/* 当每页显示数量发生变化时触发 */
const handleSizeChange = (val: number) => {
  userTit.limit = val
  /* 重新发起获取所有用户请求 */
  getUserList(userTit.page, userTit.limit, userTit.username)
}
/* 当当前页数发生变化是触发 */
const handleCurrentChange = (val: number) => {
  userTit.page = val
  /* 重新发起获取所有用户请求 */
  getUserList(userTit.page, userTit.limit, userTit.username)
}
/* 添加用户 */
const addUser = () => {
  /* 切换到添加用户界面 */
  toggleDrawer.value = true
  /* 清除数据 */
  Object.assign(addUserOrUpdate, {
    username: '',
    name: '',
    password: '',
    id: 0,
  })
}
/* 取消添加 */
const cancelAdd = () => {
  /* 关闭添加抽屉 */
  toggleDrawer.value = false
}
/* 确认添加 发起添加或者修改请求 */
const save = async () => {
  /* 关闭抽屉 */
  /* 对表单进行检验 */
  await userForm.value?.validate()
  /* 保存按钮:添加新的用户|更新已有的用户账号信息 */
  const { data: res } = await reqAddOrUpdateUserAPI(addUserOrUpdate)
  /* 添加或者更新成功 */
  if (res.code == 200) {
    /* 关闭抽屉 */
    toggleDrawer.value = false
    /* 提示消息 */
    ElMessage({
      type: 'success',
      message: addUserOrUpdate.id ? '更新成功' : '添加成功',
    })
    /* 获取最新的全部账号的信息 */
    /* getHasUser (userParams.id ? pageNo.value : 1);*/
    /* 浏览器自动刷新一次 */
    window.location.reload()
  } else {
    /* 关闭抽屉 */
    toggleDrawer.value = false
    /* 提示消息 */
    ElMessage({
      type: 'error',
      message: addUserOrUpdate.id ? '更新失败' : '添加失败',
    })
  }
}
/* 编辑角色 */
const editUser = (row: records) => {
  toggleDrawer.value = true
  /* 拷贝需要秀嘎的数据 */
  Object.assign(addUserOrUpdate, row)
}
/* 分配角色 */
const distributeUser = async (row: records) => {
  /* 拷贝 当前用户信息*/
  Object.assign(addUserOrUpdate, row)
  /* 获取全部信息角色 */
  const { data: res }: resAllRolesList = await reqGetAllRoleListAPI(
    row.id as number,
  )
  /* 对返回数据进行校验 */
  if (res.code != 200) ElMessage.error('获取失败')
  /* 获取成功对数据进行赋值 */
  AllRoleList.value = res.data.allRolesList /* 全部角色属性 */
  curRoleList.value = res.data.assignRoles /* 当前角色已有权限 */
  toggleDrawer1.value = true
}
/* 全选按钮 */
const handleCheckAllChange = (val: boolean) => {
  curRoleList.value = val ? AllRoleList.value : []
  indeterminate.value = false
}
/* 计算全选 */
watch(
  () => curRoleList.value.length,
  () => {
    indeterminate.value = checkAll.value =
      curRoleList.value.length == AllRoleList.value.length ? true : false
  },
)
/* 提交修改属性 */
const saveRole = async () => {
  /* 搜集参数 */
  let data: any = {
    userId: addUserOrUpdate.id as number,
    roleIdList: curRoleList.value.map((item) => {
      return item.id as number
    }),
  }
  /* 发起请求 */
  const { data: res }: any = await reqSetUserRoleAPI(data)
  if (res.code != 200) ElMessage.error('添加失败')
  ElMessage.success('添加成功')
  getUserList(userTit.page, userTit.limit, userTit.username)
  toggleDrawer1.value = false
}
/* 删除单个用户 */
const deletUser = async (row: records) => {
  const { data: res }: any = await reqDeletUserAPI(row.id as number)
  if (res.code != 200) ElMessage.error('删除失败')
  ElMessage.success('删除成功')
  getUserList(userTit.page, userTit.limit, userTit.username)
}
/* 批量删除 */
const deletUserList = async () => {
  let idsList: any = selectIdArr.value.map((item) => {
    return item.id
  })
  const { data: res }: any = await reqDeletUserListAPI(idsList)
  if (res.code != 200) ElMessage.error('删除失败')
  ElMessage.success('删除成功')
  getUserList(userTit.page, userTit.limit, userTit.username)
}
/* 搜索 */
const search = async () => {
  getUserList(userTit.page, userTit.limit, userTit.username)
  /* 清空数据 */
  userTit.username = ''
}
</script>

<style lang="scss" scoped>
.main {
  .seachForm {
    @include flexible(center);
    justify-content: space-between;
  }
}
</style>
